#import <Foundation/Foundation.h>

NSString *const kLineCount = @"LineCount";
NSString *const kWordCount = @"WordCount";
NSString *const kByteCount = @"ByteCount";
NSString *const kURLString = @"URLString";

int main (int argc, const char * argv[]) {
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
	
	if (argc >= 2)
	{
		NSString *fileName = [NSString stringWithCString:argv[1]
												encoding:NSASCIIStringEncoding];
		NSStringEncoding encoding;
		NSError *theError;
		
		NSString *fileContent = [NSString stringWithContentsOfFile:fileName 
													  usedEncoding:&encoding
															 error:&theError];
		NSScanner *scanner = [NSScanner scannerWithString:fileContent];
		NSCharacterSet *lineFeeds = [NSCharacterSet characterSetWithCharactersInString:@"\n\r"];
		NSMutableArray *dataArray = [NSMutableArray array];
		NSMutableArray *keyArray = [NSMutableArray array];
		NSArray *oneLineData;
		int lineCount;
		int wordCount;
		int byteCount;
		NSString *countFileName;
		
		while (![scanner isAtEnd])
		{
			[scanner scanInt:&lineCount];
			[scanner scanInt:&wordCount];
			[scanner scanInt:&byteCount];
			[scanner scanUpToCharactersFromSet:lineFeeds
									intoString:&countFileName];
			oneLineData = [NSArray arrayWithObjects:[NSNumber numberWithInt:lineCount]
						   ,[NSNumber numberWithInt:wordCount]
						   ,[NSNumber numberWithInt:byteCount]
						   ,nil];
			[dataArray addObject:oneLineData];
			[keyArray addObject:countFileName];
		}
		NSMutableDictionary *rootObject = [NSMutableDictionary dictionaryWithObjects:dataArray
																			 forKeys:keyArray];
		
		
		NSString *errorDescription;
		NSData *plistData = [NSPropertyListSerialization dataFromPropertyList:(id)rootObject 
																	   format:NSPropertyListXMLFormat_v1_0
															 errorDescription:&errorDescription]; 
		
		if (plistData)
		{
			fileName = [[fileName stringByDeletingLastPathComponent] stringByAppendingString:@"/wc_out.plist"];
			[plistData writeToFile:fileName
						atomically:YES];
		}
		else
		{
			NSLog(errorDescription);
			[errorDescription release];
		}
		
	}
	
    [pool drain];
    return 0;
}
